<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    div{
        width: 200px;
        height: 200px;
        position: absolute;
        left: 0;
        top: 0;
        text-align: center;
        line-height: 200px;
        background: peachpuff;
    }
</style>
<body>
    <div>box</div>
    <script>
        var box =document.querySelector('div')
        box.onmousedown = function(e){
            var wid = e.offsetX
            var heg = e.offsetY
            var box1x = box.offsetWidth
            var box1y = box.offsetHeight
            document.onmousemove = function(e){
                //先运算
                var x = e.clientX - wid
                var y = e.clientY - heg
                //再判断
                if(x > window.innerWidth-box1x){
                    x = window.innerWidth-box1x
                }
                if(x < 0){
                    x = 0
                }
                if(y<0) y=0
                if(y>window.innerHeight-box1y){
                    y = window.innerHeight-box1y
                }
                // 在赋值
                box.style.left = x  +'px'
                box.style.top = y  +'px'
            }
            document.onmouseup = function(){
                document.onmousemove = null
            }
            return false
        }
    </script>
</body>
</html>